﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using ZeroSum.DependencyInjection.Attributes;
using ZeroSum.Domain.Repositories;
using ZeroSum.Extend.EFCore.MySql.Extensions;
using ZeroSum.Plugin.Authorization.Datas.Services.Menus;
using ZeroSumZSA.Core.Aggregates.MenuAggregate;

namespace ZeroSumZSA.Core.DomainServices.Menus;

[Register(ServiceLifetime.Transient)]
public class MenuDomainService : MenuBaseDomainService<Menu>, IMenuDomainService
{
    public MenuDomainService(IRepository<Menu, long> menuRepository) : base(menuRepository)
    {
    }

    public IQueryable<Menu>? Query(string keyword)
    {
        var result = !string.IsNullOrEmpty(keyword?.Trim());
        var query = QueryByEntity<Menu>.Of(
            query => query.WhereIf(result,
                u => EF.Functions.Like(u.Name!, $"%{keyword!.Trim()}%") ||
                     EF.Functions.Like(u.Code!, $"%{keyword.Trim()}%")).OrderBy(x => x.Sort));
        return null;
    }

    public async Task<bool> CheckForPermission(IList<long> roleIds, string? permission)
    {
        var query = QueryByEntity<Menu>.Of(q =>
            q.Where(x => x.Roles!.Any(r => roleIds.Contains(r.Id)))
                .Where(x => x.Permission == permission)
        );
        return await MenuRepository.ExistedAsync(query);
    }
}